package com.example.myys.ui.page.mhPage

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component1
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component2
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.NativeKeyEvent
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.SubcomposeAsyncImage
import coil3.request.ImageRequest
import coil3.request.crossfade
import com.example.myys.ui.Resource
import com.example.myys.ui.StateHandler
import com.example.myys.viewModel.mhModel.MhNrViewModel
import kotlinx.coroutines.launch
import my.nanihadesuka.compose.LazyColumnScrollbar
import my.nanihadesuka.compose.ScrollbarSettings

@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
@Composable
@Preview
fun MhReaderPage(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    url: String? = "",
    dataId: String? = "0",
) {
    val xsNrViewModel: MhNrViewModel = viewModel()
    val context = LocalContext.current
    val zjlbState by xsNrViewModel.zjlbState.collectAsState()
    val nrState by xsNrViewModel.nrState.collectAsState()

    //焦点
    val (mainFocus, leftFocus) = FocusRequester.createRefs()

    StateHandler(state = zjlbState) { resource ->
        resource.data?.let { zjlbList ->
            val state =
                rememberPagerState(pageCount = { zjlbList.size }, initialPage = 0)
            LaunchedEffect(Unit) {
                snapshotFlow { state.currentPage }.collect { page ->
                    // 在这里处理翻页事件，例如打印当前页码
                    //println("Current page: $page")
                    if (zjlbList.size > page) {
                        xsNrViewModel.getChapterContent(
                            zjlbList[page].url,
                            zjlbList[page].id,
                            zjlbList[page].dataBeanId
                        )
                    }
                }
            }
            SideEffect {
                mainFocus.requestFocus()
                mainFocus.captureFocus()
            }

            val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
            val scope = rememberCoroutineScope()
            val listState = rememberLazyListState()
            val scrollState = rememberLazyListState()

            ModalNavigationDrawer(
                drawerState = drawerState,
                drawerContent = {
                    ModalDrawerSheet {
                        Text("目录", modifier = Modifier.padding(16.dp))
                        Divider()
                        LazyColumnScrollbar(
                            state = listState,
                            settings = ScrollbarSettings.Default
                        ) {
                            LazyColumn(
                                state = listState, modifier = Modifier
                                    .focusRequester(leftFocus)
                            ) {
                                itemsIndexed(zjlbList) { index, item ->
                                    NavigationDrawerItem(
                                        label = { Text(text = item.name) },
                                        selected = false,
                                        onClick = {
                                            scope.launch {
                                                state.animateScrollToPage(item.index, 0f)
                                                drawerState.apply {
                                                    if (isClosed) {
                                                        leftFocus.requestFocus()
                                                        open()
                                                    } else {
                                                        leftFocus.freeFocus()
                                                        mainFocus.captureFocus()
                                                        mainFocus.requestFocus()
                                                        close()
                                                    }
                                                }
                                            }
                                        }
                                    )
                                }
                            }
                        }
                    }
                }) {
                HorizontalPager(
                    state = state,
                    modifier = Modifier
                        .clickable {
                            scope.launch {
                                drawerState.apply {
                                    if (isClosed) {
                                        Toast
                                            .makeText(context, "打开", Toast.LENGTH_SHORT)
                                            .show()
                                        open()
                                    } else {
                                        close()
                                    }
                                }
                            }
                        }
                        .onKeyEvent { keyEvent ->
                            if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_CENTER) {
                                scope.launch {
                                    drawerState.apply {
                                        if (isClosed) {
                                            Toast
                                                .makeText(context, "打开1", Toast.LENGTH_SHORT)
                                                .show()
                                            mainFocus.freeFocus()
                                            leftFocus.captureFocus()
                                            leftFocus.requestFocus()
                                            open()
                                        } else {
                                            close()
                                        }
                                    }
                                }
                                return@onKeyEvent true
                            } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_DOWN) {
                                scope.launch {
                                    scrollState.animateScrollToItem(
                                        scrollState.firstVisibleItemIndex,
                                        scrollState.firstVisibleItemScrollOffset + 700
                                    )
                                }
                                return@onKeyEvent true
                            } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_UP) {
                                scope.launch {
                                    if (scrollState.firstVisibleItemIndex - 1 < 0) {
                                        scrollState.animateScrollToItem(0)
                                    } else {
                                        scrollState.animateScrollToItem(scrollState.firstVisibleItemIndex - 1)
                                    }
                                }
                                return@onKeyEvent true
                            } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_LEFT) {
                                scope.launch {
                                    state.animateScrollToPage(state.currentPage - 1, 0f)
                                    scrollState.animateScrollToItem(0)
                                }
                                return@onKeyEvent true
                            } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_RIGHT) {
                                scope.launch {
                                    state.animateScrollToPage(state.currentPage + 1, 0f)
                                    scrollState.animateScrollToItem(0)
                                }
                                return@onKeyEvent true
                            }
                            false
                        }
                        .focusRequester(mainFocus)
                        .focusable(),
                    flingBehavior = PagerDefaults.flingBehavior(
                        state = state,
                        snapPositionalThreshold = 0.1f
                    ),
                ) { currentPage ->
                    Toast.makeText(context, "第" + currentPage + "页", Toast.LENGTH_SHORT).show()
                    nrState?.let {
                        MhContentViewer(
                            titleName = zjlbList[currentPage].name,
                            currentPage = currentPage,
                            pageCount = state.pageCount,
                            url = zjlbList[currentPage].url,
                            id = zjlbList[currentPage].id,
                            dataBeanId = zjlbList[currentPage].dataBeanId,
                            xsNrViewModel = xsNrViewModel,
                            nrState = nrState,
                            scrollState = scrollState
                        )
                    }
                }
            }
        }
    }

    LaunchedEffect(Unit) {
        Toast.makeText(context, "页面开始1", Toast.LENGTH_SHORT).show()
        if (url != null && dataId != null) {
            xsNrViewModel.getComicChapterList(url, dataId.toInt())
        }
    }
    //生命周期
    DisposableEffect(lifecycleOwner) {
        //创建观察者
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_START) {
                Toast.makeText(context, "页面开始", Toast.LENGTH_SHORT).show()

            }
        }
        //添加观察者到生命周期
        lifecycleOwner.lifecycle.addObserver(observer)
        //页面销毁
        onDispose {
            Toast.makeText(context, "销毁页面", Toast.LENGTH_SHORT).show()
            //从生命周期中移除观察者
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
}

@Composable
fun MhContentViewer(
    titleName: String,
    padding: Dp = 16.dp,
    lineHeight: TextUnit = 39.sp,
    fontSize: TextUnit = 18.sp,
    letterSpacing: TextUnit = 2.sp,
    currentPage: Int,
    pageCount: Int,
    url: String,
    id: Int,
    dataBeanId: Int,
    xsNrViewModel: MhNrViewModel,
    nrState: Resource<String>,
    scrollState: LazyListState
) {
    /*LaunchedEffect(Unit) {
            xsNrViewModel.getChapterContent(url,id,dataBeanId)
    }*/
    StateHandler(state = nrState) { resource ->
        // 创建一个滚动状态
        val scope = rememberCoroutineScope()
        Column {
            //标题
            Text(
                modifier = Modifier.padding(10.dp),
                text = titleName,
                textAlign = TextAlign.Left,
                fontSize = 20.sp
            )
            //内容
            resource.data?.let {
                val imags = it.split(',')
                LazyColumn(
                    state = scrollState, modifier = Modifier
                        .fillMaxSize()
                        .weight(1f)
                ) {
                    itemsIndexed(imags) { index, item ->
                        SubcomposeAsyncImage(
                            modifier = Modifier
                                .fillMaxSize(),
                            model = ImageRequest.Builder(LocalContext.current)
                                .data(item)
                                .crossfade(true)
                                .build(),
                            onError = {
                                it.result.throwable.printStackTrace()
                                Log.e("SubcomposeAsyncImage", item)
                            },
                            error = { it.result },
                            contentDescription = "",
                            loading = { CircularProgressIndicator() })
                    }
                    item {
                        Text(
                            modifier = Modifier
                                .fillMaxWidth(),
                            text = "本章完",
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
            //页脚
            Text(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = padding),
                textAlign = TextAlign.End,
                lineHeight = lineHeight,
                letterSpacing = letterSpacing,
                fontSize = 12.sp,
                text = "${currentPage}/${pageCount - 1}"
            )
        }
    }

}
